package rensoft.android;

import static rensoft.java.lang.Lang.map;

import android.app.Activity;
import android.os.Bundle;
import rensoft.android.lang.IRequest;
import rensoft.android.view.ErrorDialogPresenter;
import rensoft.java.collections.Map;

public abstract class MainActivityPresenter extends ActivityPresenter implements
    IMainActivityPresenter {

  private static IMainActivityPresenter instance;

  public static IMainActivityPresenter getInstance() {
    return instance;
  }

  private final ErrorDialogPresenter errorPresenter;
  private final int requestFailedMessageId;
  private final int layoutId;

  public MainActivityPresenter(Activity activity, int layoutId, int requestFailedMessageId) {
    super(activity);
    this.layoutId = layoutId;
    this.requestFailedMessageId = requestFailedMessageId;
    errorPresenter = createErrorPresenter();
    instance = this;
  }

  public void onBackPressed() {
    activity.moveTaskToBack(true);
  }

  @Override
  public void onCreate(Bundle state) {
    setContentView(layoutId);
    super.onCreate(state);
  }

  @Override
  public void onException(int messageId, String message, String details) {
    errorPresenter.showErrorDialog(messageId, message, details);
  }

  public void onRequestFailed(IRequest request) {
    onException(requestFailedMessageId, request.getExceptionMessage(), request
        .getExceptionDetails());
  }

  public Object onRetainNonConfigurationInstance() {
    Map<String, Object> stateMap = map();
    onRetainNonConfigurationInstance(stateMap);
    if (stateMap.isEmpty()) return null;
    return stateMap;
  }

  protected abstract ErrorDialogPresenter createErrorPresenter();
}
